package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月30日16:56
 */

@WebServlet("/findAll")
public class EmpListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";

        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("<meta charset='UTF-8'>");
        out.print(" <title>员工列表</title>");
        out.print("</head>");
        out.print("<h1>员工列表</h1>");
        out.print("<a>添加员工</a>");
        out.print("<body>");
        out.print("<table border='1px'>");
        out.print("<thead>");
        out.print(" <tr>");
        out.print(" <th>编号</th>");
        out.print("<th>姓名</th>");
        out.print("<th>工资</th>");
        out.print("<th>操作</th>");
        out.print("</tr>");
        out.print("</thead>");
        out.print(" <tbody>");


        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select ")
                    .append(" id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp  ")
                    .toString();
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                out.print("<tr>");
                out.print("<td>"+rs.getInt("id")+"</td>");
                out.print("<td>"+rs.getString("name")+"</td>");
                out.print("<td>"+rs.getDouble("salary")+"</td>");
                out.print("<td><a href='showModifyEmp?id="+rs.getInt("id")+"'>修改</a>");
                out.print("<a href='deleteEmp?id="+rs.getInt("id")+"'>删除</a></td>");
                out.print("</tr>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //一定记得关闭资源
        }
        out.print("</tbody>");
        out.print("</table>");
        out.print("</body>");
        out.print("</html>");



    }
}
